package com.kandinfo.survey.weixin.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.CredentialsException;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kandinfo.base.common.dto.ResultDto;
import com.kandinfo.base.common.dto.ResultDtoFactory;
import com.kandinfo.base.common.dto.SignInDto;
import com.kandinfo.base.common.dto.annotation.OnValid;
import com.kandinfo.base.common.util.AppConfigUtil;
import com.kandinfo.base.common.util.web.WebUtil;
import com.kandinfo.base.common.validation.ValidateException;
import com.kandinfo.base.security.SecurityContext;
import com.kandinfo.base.security.constants.RoleConstants;
import com.kandinfo.base.security.domain.User;
import com.kandinfo.base.security.dto.UserDto;
import com.kandinfo.base.security.service.UserService;
import com.kandinfo.survey.weixin.dto.WxJsConfigureDto;
import com.kandinfo.survey.weixin.mongo.WxConfigure;
import com.kandinfo.survey.weixin.service.WxAuthService;
import com.kandinfo.survey.weixin.service.WxMongoAccessTokenService;
import com.tencent.common.Configure;
import com.tencent.common.RandomStringGenerator;

/**
 * 
 * 微信用户注册授权
 * 
 * @author
 *
 */
@Controller
@RequestMapping(value = "weixin/wx-auth")
public class WxAuthController {

    @Autowired
    private UserService userService;
    @Autowired
    private WxAuthService wxAuthService;
    @Autowired
    private WxMongoAccessTokenService wxMongoAccessTokenService;
   
    /**
     * 获取token
     * @return
     */
    @CrossOrigin
    @ResponseBody
    @RequestMapping(value="/getAccessToken", method = RequestMethod.GET)
    public ResultDto getAccessToken() {
		String appId = AppConfigUtil.getConfig("wechat.appId");
		String appSecret = AppConfigUtil.getConfig("wechat.appSecret");
    	WxConfigure wxConfigure = wxMongoAccessTokenService.getWxConfigure(appId, appSecret);
    	wxConfigure.setAppSecret(null);
    	return ResultDtoFactory.toAck("查询成功", wxConfigure);
    }

    /**
     * 该方法强制刷新token，一般在token出现故障了则重置token
     * @return
     */
    @ResponseBody
    @RequiresRoles(value = RoleConstants.SUPER_ADMIN)
    @RequestMapping(value="/reflushAccessToken", method = RequestMethod.GET)
    public ResultDto reflushAccessToken() {
		String appId = AppConfigUtil.getConfig("wechat.appId");
		String appSecret = AppConfigUtil.getConfig("wechat.appSecret");
    	WxConfigure wxConfigure = wxMongoAccessTokenService.resetAccessToken(appId, appSecret);
    	wxConfigure.setAppSecret(null);
    	return ResultDtoFactory.toAck("刷新成功", wxConfigure);
    }
    
	// 获取jssdk权限
	@RequestMapping(value = "/getJsConfigure", method = RequestMethod.POST)
	@ResponseBody
	public ResultDto getJsConfigure(String url) {
		
		String appId = AppConfigUtil.getConfig("wechat.appId");
		String appSecret = AppConfigUtil.getConfig("wechat.appSecret");
		WxConfigure configure = wxMongoAccessTokenService.getWxConfigure(appId, appSecret);
		
		WxJsConfigureDto jsConfigure = new WxJsConfigureDto();
		jsConfigure.setAppId(Configure.getAppid());
		jsConfigure.setNonceStr(RandomStringGenerator.getUUID());
		jsConfigure.setTimestamp(String.valueOf(System.currentTimeMillis()));
		jsConfigure.setUrl(url);
		jsConfigure.signature(configure.getJsapiTicket());
		
		return ResultDtoFactory.toAckNomessage("获取微信授权完成", jsConfigure);
	}

    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto addUser(@OnValid @RequestBody UserDto adminUserDto, BindingResult result, Model model) {

        String username = adminUserDto.getUsername().trim();
        adminUserDto.setUsername(username);

        User checkUser = userService.findUserByUsername(adminUserDto.getUsername());
        if (checkUser != null) {
            return ResultDtoFactory.toNack("此用户名已经存在!");
        } else {
        	wxAuthService.registWxUser(adminUserDto);
            return ResultDtoFactory.toAck("新建成功");
        }
    }
    
    @RequestMapping(value = "/authc", method = RequestMethod.POST)
    @ResponseBody
    public ResultDto doLoginAuthc(@OnValid @RequestBody SignInDto signInDto, BindingResult result, HttpSession session) {

        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        Session newSession = null;
        try {
            newSession=SecurityContext.login(signInDto.getUsername(), signInDto.getPassword(),signInDto.isRememberMe());
            
        } catch (AccountException e) {
            result.rejectValue("username", "error.invalid.username");
        } catch (CredentialsException e) {
            result.rejectValue("password", "error.invalid.password");
        }
        if (result.hasErrors()) {
            throw new ValidateException(result);
        }
        User loginUser = userService.findUserByUsername(signInDto.getUsername());
        newSession.setAttribute("user", loginUser);
        
        return ResultDtoFactory.toRedirect(WebUtil.getFullUrlBasedOn("/web/home4wx"));
    }
    

}
